/*
 * @Author: zyl
 * @Date: 2020-10-23 21:09:45
 * @LastEditTime: 2020-10-23 21:31:01
 * @LastEditors: Please set LastEditors
 * @Description: BIO的简单使用
 * @FilePath: \javaCode\java8newPro\io\BIO\BIOServer.java
 */
package java8newPro.io.BIO;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOServer {
    // 创建线程池 来一个任务就产生一个线程，所以使用CachedPool
    public static void main(String[] args) throws IOException {
        ExecutorService service = Executors.newCachedThreadPool();
        // 监听6666端口
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("Server start.....");
        while (true) {
            final Socket socket = serverSocket.accept();// 也会阻塞
            System.out.println("一个客户端连接");
            service.execute(()->{
                byte[] bytes = new byte[1024];
                try {
                    InputStream inputStream = socket.getInputStream();
                    while (true) {
                        int read = inputStream.read(bytes);
                        if(read!=-1){
                            System.out.println(read);
                            System.out.println("线程"+Thread.currentThread().getName()+"收到的信息："+new String(bytes,0,read));
                        }else break;
                    }
                } catch (Exception e) {
                    //TODO: handle exception
                    e.printStackTrace();
                }finally{
                    try {
                        System.out.println("Close Connection...");
                    } catch (Exception e) {
                        //TODO: handle exception
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}
